from sqlalchemy import Column, Integer, String, Index
from sqlalchemy.orm.session import Session

from airflow.exceptions import AirflowException
from airflow.models.base import Base
from airflow.utils.session import provide_session

'''
category 0 email, 1 dingding
'''


class Alert(Base):
    __tablename__ = "idata_alert"

    id = Column(Integer, primary_key=True, autoincrement=True)
    project_id = Column(Integer)
    category = Column(Integer)
    name = Column(String(64))
    content = Column(String(255))

    __table_args__ = (
        Index('category_content', category, content),
    )

    @staticmethod
    @provide_session
    def get_alert(alert_id, session: Session = None):
        return session.query(Alert).filter(Alert.id == alert_id).first()

    @provide_session
    def insert(self, session: Session = None):
        if self.category == 0:
            if not self.content:
                raise AirflowException('钉钉 url 不能为空')
            if not self.content.startswith('https://'):
                raise AirflowException('钉钉 url 格式不合法')
        session.add(self)

    @staticmethod
    @provide_session
    def query_options(project_id, category=None, session: Session = None):
        qry = session.query(Alert).filter(Alert.project_id == project_id)
        if category:
            qry = qry.filter(Alert.category == category)
        rs = [{'id': it.id, 'name': it.name} for it in qry.all()]
        return rs

    @staticmethod
    @provide_session
    def query_page(project_id, category=None, page=1, page_size=10, session: Session = None):
        qry = session.query(Alert).filter(Alert.project_id == project_id)
        if category:
            qry = qry.filter(Alert.category == category)
        alert_page = qry.paginate(page=page, per_page=page_size, error_out=False)
        results = alert_page.to_json()
        results['items'] = [it.to_json() for it in results['items']]
        return results

    @provide_session
    def update(self, session: Session = None):
        if not self.content:
            raise AirflowException('钉钉 url 不能为空')
        if not self.content.startswith('https://'):
            raise AirflowException('钉钉 url 格式不合法')
        session.merge(self)

    @provide_session
    def delete(self, session: Session = None):
        if self.id:
            session.query(Alert).filter(Alert.id == self.id).delete()

    def to_json(self):
        data = {'id': self.id, 'category': self.category, 'name': self.name, 'content': self.content}
        if data['category'] == 0:
            data['category_name'] = '钉钉'
        return data
